<?php

namespace common\models;

use Yii;

/**
 * This is the model class for table "admin".
 *
 * @property string $id
 * @property string $name
 * @property string $section_id
 * @property string $password
 */
class Admin extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'admin';
    }

    /**
     * @inheritdoc
     */



    public function rules()
    {
        return [
            [['name', 'section_id',], 'required'],
            [['section_id'], 'integer'],
            [['name'], 'string', 'max' => 50],
        ];
    }
    public function attributes()
    {
        return array_merge(parent::attributes(),['roles']);
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'name' => '用户名',
            'section_id' => '部门',
            'password' => '密码(默认:123456)',
            'roles' => '角色',
        ];
    }

    /**
     * 获取部门
     * @return \yii\db\ActiveQuery
     */
    public function getSection()
    {
        return $this->hasOne(Section::className(),['id'=>'section_id']);
    }

    public function beforeSave($insert)
    {
        if(parent::beforeSave($insert))
        {
            $post = Yii::$app->request->post();
            $this->password = md5($post['Admin']['password']);
            return true;
        }
        else
        {
            return false;
        }
    }

    /**
     * 保存后
     * @param bool $insert
     * @param array $changedAttributes
     */
    public function afterSave($insert, $changedAttributes)
    {
        parent::afterSave($insert, $changedAttributes);
        $post = Yii::$app->request->post();
        $roles = $post['Admin']['roles'];
        $id = $this->id;
        //生成插入的数组
        $data = [];
        foreach($roles as $v)
        {
            $_data=[];
            $_data[] = $id;
            $_data[] = $v;
            $data[] = $_data;
        }
        if($insert)
        {//新增,

        }
        else
        {//修改
            //先删除对应的角色
            Yii::$app->db->createCommand()->delete('adminrole',['admin_id'=>$id])->execute();

        }
        //增加对应的角色
        Yii::$app->db->createCommand()->batchInsert('adminrole', ['admin_id', 'role_id'], $data)->execute();
    }
}
